package com.ruoyi.sale.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.mapper.ErpWarehouseOutMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.sale.mapper.ErpOrderMapper;
import com.ruoyi.sale.service.IErpOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-10
 */
@Service
public class ErpOrderServiceImpl implements IErpOrderService
{
    private static final Logger log = LoggerFactory.getLogger(ErpOrderServiceImpl.class);
    @Autowired
    private ErpOrderMapper erpOrderMapper;
    @Autowired
    private ErpWarehouseOutMapper erpWarehouseOutMapper;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public ErpOrder selectErpOrderById(int id)
    {
        return erpOrderMapper.selectErpOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param erpOrder 订单
     * @return 订单
     */
    @Override
    public List<ErpOrder> selectErpOrderList(ErpOrder erpOrder)
    {
        return erpOrderMapper.selectErpOrderList(erpOrder);
    }

    @Override
    public List<ErpGoodss> selectErpGoodsList(ErpGoodss erpGoodss) {
        return erpOrderMapper.selectErpGoodsList(erpGoodss);
    }

    /**
     * 新增订单
     *
     * @param erpOrder 订单
     * @return 结果
     */
    @Override
    public int insertErpOrder(ErpOrder erpOrder)
    {
        if (erpOrder.getWarehouseName() == null && erpOrder.getWarehouseId() != null) {
            String warehouseName = erpOrderMapper.selectWarehouseNameById(erpOrder.getWarehouseId());
            erpOrder.setWarehouseName(warehouseName);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());

        // 获取当天已有的最大订单编号
        String maxOrderSn = erpOrderMapper.selectMaxOrderSnByDate(dateStr);
        int sequence = 1;
        if (maxOrderSn != null) {
            String sequenceStr = maxOrderSn.substring(maxOrderSn.length() - 4);
            sequence = Integer.parseInt(sequenceStr) + 1;

        }

        // 生成订单编号
        String orderSn = "PO" + dateStr + String.format("%04d", sequence);
        erpOrder.setSn(orderSn);

        erpOrder.setCreateTime(DateUtils.getNowDate());
        erpOrder.setStatus("待审核"); // 设置默认状态
        erpOrder.setPaymentStatus("未支付"); // 设置默认支付状态


        int result = erpOrderMapper.insertErpOrder(erpOrder);
        if (result > 0 && erpOrder.getGoodsList() != null) {
            // 保存商品明细
            for (ErpGoodss goods : erpOrder.getGoodsList()) {
                Map<String, Object> params = new HashMap<>();
                params.put("orderId", erpOrder.getId());
                params.put("goodsId", goods.getId());
                params.put("countNum", goods.getNum());
                params.put("price", goods.getPrice());
                params.put("createTime", new Date());

                erpOrderMapper.insertOrderGoods(params);
            }
        }
        return result;
    }

    /**
     * 修改订单
     *
     * @param erpOrder 订单
     * @return 结果
     */
    @Override
    public int updateErpOrder(ErpOrder erpOrder)
    {
        erpOrder.setUpdateTime(DateUtils.getNowDate());
        return erpOrderMapper.updateErpOrder(erpOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteErpOrderByIds(int[] ids)
    {
        return erpOrderMapper.deleteErpOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteErpOrderById(int id)
    {
        return erpOrderMapper.deleteErpOrderById(id);
    }


    @Override
    public List<WarehouseDept> selectWarehouseDeptList() {
        return erpOrderMapper.selectWarehouseDeptList();
    }
    @Override
    public int auditErpOrder(int id) {
        ErpOrder erpOrder = erpOrderMapper.selectErpOrderById(id);
        if (erpOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 1. 更新订单状态为"待出库"
        erpOrder.setStatus("待出库");
        int result = erpOrderMapper.updateErpOrder(erpOrder);

        // 2. 创建出库单
        if (result > 0) {
            ErpWarehouseOut out = new ErpWarehouseOut();
            out.setSn("OUT" + System.currentTimeMillis()); // 生成出库单编号
            out.setOrderIdList(String.valueOf(id)); // 关联订单ID
            out.setOrderSnList(erpOrder.getSn()); // 关联订单编号
            out.setWarehouseId(erpOrder.getWarehouseId()); // 仓库ID
            out.setWarehouseName(erpOrder.getWarehouseName()); // 仓库名称
            out.setDeptId(erpOrder.getDeptId()); // 部门ID
            out.setDeptName(erpOrder.getDeptName()); // 部门名称
            out.setMemberRealName(erpOrder.getOwnerName()); // 客户名称
            out.setMemberMobile(erpOrder.getOwnerMobile()); // 客户电话
            out.setShipAddr(erpOrder.getShipAddress()); // 收货地址
            out.setDeliveryType(erpOrder.getDeliveryType()); // 配送方式
            out.setStatus("待发货"); // 出库单状态
            out.setCreateTime(DateUtils.getNowDate());

            // 保存出库单
            erpWarehouseOutMapper.insertErpWarehouseOut(out);

            // 更新订单的出库单ID
            erpOrder.setWarehouseOutId(out.getId());
            erpOrderMapper.updateErpOrder(erpOrder);
        }

        return result;
    }


    @Override
    public int outboundErpOrder(int id) {
        ErpOrder erpOrder = erpOrderMapper.selectErpOrderById(id);
        if (erpOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 检查 warehouseId 是否有效
        if (erpOrder.getWarehouseId() == null) {
            throw new RuntimeException("订单未关联仓库");
        }

        List<ErpGoodss> goodsList = this.getOrderGoodsByOrderId((long) id);
        if (goodsList == null || goodsList.isEmpty()) {
            throw new RuntimeException("订单无商品明细");
        }

        // 扣减库存
        for (ErpGoodss goods : goodsList) {
            int affectedRows = erpOrderMapper.reduceProductStock(
                    goods.getId(),
                    goods.getCountNum(),
                    erpOrder.getWarehouseId()
            );

            if (affectedRows == 0) {
                throw new RuntimeException(
                        "商品 " + goods.getName() + " 扣减库存失败，可能库存不足"
                );
            }
        }

        // 更新订单状态为 "待发货"
        erpOrder.setStatus("待发货");
        return erpOrderMapper.updateErpOrder(erpOrder);
    }

    private void reduceStock(Long productId, Integer quantity, Long warehouseId) {

        // 扣减库存
        int affectedRows = erpOrderMapper.reduceProductStock(productId, quantity, warehouseId);
        if (affectedRows == 0) {
            throw new RuntimeException("扣减库存失败");
        }
    }


    @Override
    public int payErpOrder(int id) {
        ErpOrder erpOrder = erpOrderMapper.selectErpOrderById(id);
        if (erpOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        erpOrder.setPaymentStatus("已支付");
        return erpOrderMapper.updateErpOrder(erpOrder);
    }

    @Override
    public List<ErpGoodss> getOrderGoodsByOrderId(Long orderId) {
        return erpOrderMapper.selectOrderGoodsByOrderId(orderId);
    }

    @Override
    public int updateProductStock(Long productId, Long warehouseId, Integer quantity) {
        return erpOrderMapper.reduceProductStock(productId, quantity, warehouseId);
    }

    @Override
    @Transactional
    public int approveErpOrder(int id) {
        ErpOrder erpOrder = erpOrderMapper.selectErpOrderById(id);
        erpOrder.setStatus("待出库");

        // 1. 更新订单状态
        int result = erpOrderMapper.updateErpOrder(erpOrder);

        if (result > 0) {
            // 2. 获取订单商品明细
            List<ErpGoodss> goodsList = this.getOrderGoodsByOrderId((long) id);

            // 3. 创建出库单
            ErpWarehouseOut out = new ErpWarehouseOut();
            out.setSn("OUT" + System.currentTimeMillis());
            out.setOrderIdList(String.valueOf(id));
            out.setOrderSnList(erpOrder.getSn());
            out.setWarehouseId(erpOrder.getWarehouseId());
            out.setWarehouseName(erpOrder.getWarehouseName());
            out.setDeptId(erpOrder.getDeptId());
            out.setDeptName(erpOrder.getDeptName());
            out.setMemberRealName(erpOrder.getOwnerName());
            out.setMemberMobile(erpOrder.getOwnerMobile());
            out.setShipAddr(erpOrder.getShipAddress());
            out.setDeliveryType(erpOrder.getDeliveryType());
            out.setStatus("待发货");
            out.setCreateTime(DateUtils.getNowDate());

            // 保存出库单
            erpWarehouseOutMapper.insertErpWarehouseOut(out);

            // 4. 添加出库明细
            for (ErpGoodss goods : goodsList) {
                Map<String, Object> params = new HashMap<>();
                params.put("warehouseOutId", out.getId());
                params.put("orderId", id);
                params.put("orderSn", erpOrder.getSn());
                params.put("goodsId", goods.getId());
                params.put("productId", goods.getId()); // 假设商品ID和产品ID相同
                params.put("productName", goods.getName());
                params.put("productSpecification", goods.getSpecName());
                params.put("productPrice", goods.getPrice());
                params.put("outNum", goods.getCountNum());

                erpWarehouseOutMapper.insertOutItem(params);
            }

            // 5. 更新订单的出库单ID
            erpOrder.setWarehouseOutId(out.getId());
            erpOrderMapper.updateErpOrder(erpOrder);
        }

        return result;
    }

    @Override
    public int rejectErpOrder(int id) {
        ErpOrder erpOrder = erpOrderMapper.selectErpOrderById(id);
        erpOrder.setStatus("待审核");
        return erpOrderMapper.updateErpOrder(erpOrder);
    }

    @Override
    public List<ErpOrder> selectAvailableOrderList(ErpOrder erpOrder) {
        return erpOrderMapper.selectAvailableOrderList(erpOrder);
    }


}
